import { createRouter, createWebHashHistory } from 'vue-router'

import Home from '../views/home/Home.vue'
import Login from '../views/login/Login.vue'

import Register from '../views/register/Register.vue'
import Shop from '../views/shop/Shop.vue'
const routes = [
  { path: '/', redirect: '/home' },
  { path: '/home', component: Home, name: 'home' },
  { path: '/shop', component: Shop, name: 'shop' },
  {
    path: '/login',
    component: Login,
    name: 'login',
    beforeEnter: (to, from, next) => {
      // reject the navigation

      const { isLogin } = localStorage
      if (isLogin) {
        next('/home')
      }

      if (to.path === '/login' || to.path === '/register') {
        next()
      } else {
        next('/login')
      }
    }
  },
  {
    path: '/register',
    component: Register,
    name: 'register',
    // 组件内守卫
    beforeEnter: (to, from, next) => {
      // const isLogin = false
      const { isLogin } = localStorage
      if (isLogin) {
        next('/login')
      } else {
        next()
      }
    }
  }

]
const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// router.beforeEach((to, from, next) => {
//   // console.log(to)
//   // console.log(from)
//   // next()

//   //  如果登录了 放行  去的 非登录页面 直接放行   如果去的登录页面  跳转到home

//   // 如果没登录   直接去登录 那么放行  如果去别的页面   跳转到登录

//   const { isLogin } = localStorage
//   if (!isLogin) {
//     if (to.name === 'login') {
//       next()
//     } else {
//       router.push({ name: 'login' })
//     }
//   } else {
//     if (to.name === 'login') {
//       // alert(1)
//       router.push({ name: 'home' })
//       // console.log(2)
//     } else {
//       next()
//     }
//   }
// })

// 简写
router.beforeEach((to, from, next) => {
  const { isLogin } = localStorage

  // const isLogin = false
  if (isLogin || to.name === 'login' || to.name === 'register') {
    next()
  } else {
    router.push({ name: 'login' })
  }

  // 直接放行
  next()
})

export default router
